package com.watson.juc.testlist;

import javax.lang.model.element.VariableElement;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;

/**
 * 独占锁 （写锁） 一次只能被一个线程占有
 * 共享锁 （读锁） 多个线程可以同时占有
 **/
public class ReadWriteLockDemo {
    public static void main(String[] args) {
        MyCacheLock myCache = new MyCacheLock();
        for (int i = 1; i < 10; i++) {
            final int temp = i;
            new Thread(() -> {
                myCache.put(temp + "", temp);
            }, String.valueOf(i)).start();
        }

        for (int i = 0; i < 10; i++) {
            final int temp = i;
            new Thread(() -> {
                myCache.get(temp + "");
            }, String.valueOf(i)).start();
        }
    }

}

/**
 * 自定义 缓存
 */
class MyCache {
    private volatile Map<String, Object> map = new HashMap<>();

    //存 ，写
    public void put(String k, Object v) {
        System.out.println(Thread.currentThread().getName() + "写入");
        map.put(k, v);
        System.out.println(Thread.currentThread().getName() + "写入完成");
    }

    // 读 ，取
    public void get(String key) {
        System.out.println(Thread.currentThread().getName() + "开始读取");
        map.get(key);
        System.out.println(Thread.currentThread().getName() + "读取完成");
    }

}

class MyCacheLock {
    private volatile Map<String, Object> map = new HashMap<>();

    Lock lock = new ReentrantLock();
    ReadWriteLock readWriteLock = new ReentrantReadWriteLock();


    //存 ，写
    public void put(String k, Object v) {
//        lock.lock();
        readWriteLock.writeLock().lock();
        try {
            System.out.println(Thread.currentThread().getName() + "写入");
            map.put(k, v);
            System.out.println(Thread.currentThread().getName() + "写入完成");
        } catch (Exception e) {

        } finally {
//            lock.unlock();
            readWriteLock.writeLock().unlock();
        }


    }

    // 读 ，取
    public void get(String key) {
        readWriteLock.readLock().lock();

        try {
            System.out.println(Thread.currentThread().getName() + "开始读取");
            map.get(key);
            System.out.println(Thread.currentThread().getName() + "读取完成");
        } catch (Exception e) {

        } finally {
//            lock.unlock();
            readWriteLock.readLock().unlock();
        }

    }

}
